package com.jie.generator.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jie.common.annotation.Log;
import com.jie.common.controller.BaseController;
import com.jie.common.enums.BusinessType;
import com.jie.common.page.TableDataInfo;
import com.jie.common.result.R;
import com.jie.generator.entity.GenTable;
import com.jie.generator.entity.GenTableColumn;
import com.jie.generator.service.GenTableColumnService;
import com.jie.generator.service.GenTableService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @description Controller 前端控制器
 * @author: xiaojie
 * @since: 2024/12/12 0012
 */
@RestController
@RequestMapping("/tool/gen")
public class GenController extends BaseController {

    @Autowired
    private GenTableService genTableService;

    @Autowired
    private GenTableColumnService genTableColumnService;

    @ApiOperation(value = "查询数据库列表")
    @GetMapping("/db/list")
    public R dataList(GenTable genTable) {
        IPage<GenTable> list = genTableService.selectDbTableList(genTable);
        return R.ok(list);
    }

    @ApiOperation(value = "保存表结构")
    @PostMapping("/importTable")
    public R importTableSave(String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return R.ok();
    }

    @ApiOperation(value = "查询生成表列表")
    @GetMapping("/list")
    public TableDataInfo genList(GenTable genTable) {
        startPage();
        List<GenTable> list = genTableService.selectGenTableList(genTable);
        return getDataTable(list);
    }

    @ApiOperation(value = "预览代码")
    @GetMapping("/preview/{tableId}")
//    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    public R preview(@PathVariable("tableId") Long tableId) {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return R.ok(dataMap);
    }

    @ApiOperation(value = "生成代码（下载方式）")
    @GetMapping("/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }

    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @ApiOperation(value = "批量生成代码")
    @GetMapping("/download/batch")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
    }

    @ApiOperation(value = "删除代码生成")
    @DeleteMapping("/{tableIds}")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    public R remove(@PathVariable Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return R.ok();
    }

    /**
     * 查询代码生成业务
     */
    @GetMapping(value = "/table/{tableId}")
    public R getInfo(@PathVariable Long tableId) {
        GenTable table = genTableService.selectGenTableById(tableId);
        List<GenTable> tables = genTableService.selectGenTableAll();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);
        return R.ok(map);
    }

    /**
     * 修改保存代码生成业务
     */
    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @PutMapping
    public R editSave(@Validated @RequestBody GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return R.ok();
    }

    /**
     * 下载头部配置
     * @param response
     * @param data
     * @throws IOException
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IoUtil.write( response.getOutputStream(),false,data);
    }

}
